package mest.controller.hank;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import mest.entity.DictionariesOrder;
import mest.entity.plan_productjob_saleout;
import mest.entity.plan_saleout;
import mest.entity.plan_takematerial;
import mest.service.cxj.DictionariesOrderService;
import mest.service.cxj.ProductJobService;
import mest.service.hank.PlanProductjobSaleoutService;
import mest.service.hank.PlanSaleoutService;
import mest.service.hank.PlanTakematerialService;
import mest.service.hws.BomSaveManytomanyService;
import mest.util.DateUtil;
import mest.util.ResultObj;
import mest.util.hankUtil.Util_Code;
import mest.util.hankUtil.Util_CodeFactory;
import mest.util.mestUtil;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname PlanSaleout
 * @Description TODO
 * @Date 2019/12/6 15:41
 * @Created by 18416
 * @Auther: henk
 */

@RestController
@RequestMapping("/PlanSaleout")
@CrossOrigin
public class PlanSaleoutController {

    //本类
    @Resource
    private PlanSaleoutService pss;
    //流水号表
    @Resource
    private DictionariesOrderService dos;
    //查物料和产品
    @Resource
    private BomSaveManytomanyService bsmts;
    /**
     * 需要循环插入的对象接口
     */
    @Resource
    private PlanProductjobSaleoutService ppsos;


    /**
     * 1.新增
     * 2.给个接口进来果魔军用来插一插
     * url /PlanSaleout/createModel_PlanSaleout
     *
     * @param poId
     * @return
     * @throws ParseException
     */
    @RequestMapping("/createModel_PlanSaleout")
    public Object createModel_PlanSaleout(@RequestBody JSONObject json, HttpServletRequest request) throws ParseException {
        Map<String, Object> map = json.toJavaObject(Map.class);
        map.put("theirDb", mestUtil.getCompanyDB(request));
    	Long start = System.currentTimeMillis();

        Map<String, Object> modelMap = new HashMap<String, Object>();
        //System.out.println(map);
        //1.new plan_saleout对象
        plan_saleout record = new plan_saleout();
        //2.判断 传入ID是否为空
        if (!ObjectUtils.isEmpty(map.get("poId"))) {
            try {
                //3.把值 set 进 plan_takematerial对象
//                record.setTime(DateUtil.getDateTimeToDate());
//                record.setFinishStatus(0);
//                record.setPoId(Integer.valueOf(""+map.get("poId")));
                //4. 新建订单编号
                DictionariesOrder dictionaries_order = dos.selectDictionariesOrder(mestUtil.getCompanyDB(request));
                //4.(1).把结果查出来
                String number = dictionaries_order.getPlansaleoutNumber().toString();
                //4.(2).生成流水号
                //record.setTableNumber(Util_CodeFactory.create_plan_saleout_CODE(number));
                //5.把对象插入表,并返回ID
            	map.put("time", DateUtil.getDateTimeToDate());
            	map.put("finishStatus", 0);
            	map.put("tableNumber", Util_CodeFactory.create_plan_saleout_CODE(number));
                int result_id = pss.insertResult_id(map);
                if (ObjectUtils.isEmpty(result_id)) {
                    modelMap.put("code", Util_Code.number_Fail);
                    modelMap.put("msg", Util_Code.Fail_CODE);
                    return JSON.toJSONString(modelMap);
                } else {
                    //6.如果成功的情况下..  把结果返回给前端
                    modelMap.put("data", result_id);
                    modelMap.put("msg", Util_Code.Success_CODE + " 此表的ID是:" + result_id);
                    modelMap.put("code", ResultObj.CODE_SUCCESS);
                    modelMap.put("count", "model");
                    modelMap.put("psId", result_id);
                    //7.将生成编号+1
                    int i1 = dos.add_dictionaries_Order(mestUtil.getCompanyDB(request),"plansaleoutNumber");
                    List<plan_productjob_saleout> ppjslist = bsmts.selectAllModel2_saleout(mestUtil.getCompanyDB(request),Integer.valueOf(""+map.get("poId")));
                    //System.out.println("==========================");
                    //System.out.println(ppjslist.toString());
                    //System.out.println("==========================");
                    for (plan_productjob_saleout list : ppjslist) {
                        list.setPsId(result_id);
                        //System.out.println(list.toString());
                    }
                    ppsos.intsertList(ppjslist, mestUtil.getCompanyDB(request));
                    //System.out.println("插入成功");
                    modelMap.put("ppsos", "插入成功");
                    modelMap.put("耗时/ms:", (System.currentTimeMillis() - start));
                    return JSON.toJSONString(modelMap);
                }
            } catch (Exception e) {
            	e.printStackTrace();
                modelMap.put("code", Util_Code.number_Fail);
                modelMap.put("msg", Util_Code.Fail_CODE);
                modelMap.put("errmsg", e.toString());
                return JSON.toJSONString(modelMap);
            }
        } else {
            modelMap.put("code", Util_Code.number_Fail);
            modelMap.put("msg", Util_Code.Fail_CODE);
            return JSON.toJSONString(modelMap);
        }
        
    }


    /**
     * 分页查询+加过滤条件
     *
     * @param index     第几页
     * @param pageSize  页数
     * @param htmlModel 模糊查询字段
     * @param state     状态
     * @return
     */
    @RequestMapping("/queryAllModel")
    public Object queryAllModel(@RequestParam Integer index,
                                @RequestParam Integer pageSize,
                                String htmlModel,
                                @RequestParam Integer state, HttpServletRequest request) {
        Long start = System.currentTimeMillis();
        String theirDb = mestUtil.getCompanyDB(request);
        Map<String, Object> modelMap = new HashMap<String, Object>();
        try {
            List<Map> eModel = pss.queryAllModel(index,
                    pageSize, htmlModel, state, theirDb);
            //System.out.println(eModel.toString());
            if (!ObjectUtils.isEmpty(eModel)) {
                modelMap.put("data", eModel);
                modelMap.put("msg", "success");
                modelMap.put("code", 0);
                modelMap.put("count", pss.findCount(htmlModel, state, theirDb));
                modelMap.put("耗时/ms:", (System.currentTimeMillis() - start));
            } else {
                modelMap.put("msg", "此对象为空值");
            }

        } catch (Exception e) {
            modelMap.put("msg", "fales");
            modelMap.put("errmsg", e.toString());
        }
        return JSON.toJSONString(modelMap);
    }

    @RequestMapping("/changeStatus")
    public ResultObj changeStatus(@RequestBody JSONObject json,HttpServletRequest request) {
    	try {
    		
    		Map<String, Object> map = json.toJavaObject(Map.class);
    		map.put("theirDb", mestUtil.getCompanyDB(request));
    		pss.updateByPrimaryKeySelective(map);
    		return ResultObj.createSuccess();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return ResultObj.createError();
		}
    }
}
